<!--  -->
<template>
  <div class="live flex column">
    <div class="title flex shrink">
      <span class="bhead icon"> 至尊盯市 </span>
      <span class="titleTxt"
        >投资顾问意见仅作参考，不作为买卖建议。股市有风险，投资需谨慎！</span
      >
    </div>
    <div class="intro" @click="upIntro" v-show="announcement && introShow">
      <p>
        {{ announcement | short }}
      </p>
      <!-- <i class="icon" v-show="announcement.length >= 40"></i> -->
    </div>
    <!-- <div class=" intro " @click="upIntro" v-show="announcement && !introShow">
      <p>
        {{ announcement }}
      </p>
      <i class="icon zk"></i>
    </div> -->

    <div class="chatBox flex column grow" ref="chatBox" @scroll="tumble">
      <div class="chat-items-wrap flex column grow" ref="chatWrap">
        <div class="noMore flex column grow" v-if="messageList.length < 1">
          <p>暂无数据</p>
        </div>
        <div
          class="chat-item clear"
          :class="{ user: item.puiblisherid == userId }"
          v-for="item in messageList"
          :key="item.id"
        >
          <div class="time">{{ item._publishTime }}</div>
          <div class="line1 clear">
            <span class="photo">
              <img :src="item.teacherPhoto || item.userPhoto" alt />
            </span>
            <span class="name">{{ item.teacherName || item.userName }}</span>
            <span class="cerName" v-if="item.cerName">
              证书编号{{ item.cerName }}
            </span>
            <i v-if="item.user_type == 1" class="user_type"> </i>
          </div>

          <div class="line2 clear">
            <div class="content" v-html="item.content" @click="viewImg"></div>
            <template v-if="item.replyList">
              <span class="reply" v-for="i in item.replyList" :key="i.id">
                <span class="replyName"
                  >@{{ i.teacherName || i.userName }}</span
                >
                <span v-html="i.content"></span>
              </span>
            </template>
          </div>
        </div>
      </div>
    </div>
    <!-- panqiuna -->
    <div class="replyBox flex column grow shrink" v-if="false">
      <span class="toDown" @click="putDown" v-show="shrink.switch">
        {{ shrink.text }}
      </span>
      <textarea
        @keyup.enter="submit"
        placeholder="请输入内容，最多150字"
        class="flex column grow"
        v-model="content"
      ></textarea>
      <div class="toolBox flex column grow shrink clear">
        <div
          class="stockList-items top"
          v-show="listShow"
          @mouseleave="listShow = false"
        >
          <div
            class="stockList-item clear"
            v-for="item in stockList"
            :key="item.stockName"
            @click="
              choose(item.exchangeSymbols, item.stockCode, item.stockName)
            "
          >
            <span class="cell cell1" v-text="item.hqTypeLabel"></span>
            <span class="cell" v-text="item.code"></span>
            <span class="cell" v-text="item.stockName"></span>
            <span class="cell cell4" v-text="item.chiSpelling"></span>
          </div>
        </div>
        <input type="text" v-model="stock" placeholder="股票代码/名称/首字母" />
        <div class="submit tr">
          {{ count }}/150
          <span @click="submit">提交</span>
        </div>
      </div>
    </div>
    <openImg v-bind:imgSrc.sync="imgSrc"></openImg>
  </div>
</template>

<script>
import { getStockList, getInfo, getLiveList, postLive } from "../api/index";
import * as fn from "../script/utils";
import debounce from "lodash/debounce";
import { Toast } from "vant";
import format from "date-fns/format";
// import getUrlParams from "../../common/common";

import { getUrlParams } from "../script/utils";
import openImg from "../component/openImg";

const { token, productId, userId } = getUrlParams();

// const token =
//   "CN,4G3Btpq682wh2Nq1di3sjLKG8BZAM1aZiazwC6saDmIfMUeSND1ZMUa0Wpizyg8WwgEEsiXdDuXHTAGIHcx0sZsRK3xp,7O.z.vBD5BktwRMDAuUjWi9Xadl8kvifdSdcIrYrfraWf6Xuucm8z7bhuOgTmrFM36jg0F.,zPSdYK4N,DcrEhaBW4TEoOZvMqfzQ917lcI_";
// const productId = 66;
// const userId = 1121;

import behavior from "../script/behavior";
const userData = { ...behavior };
function handler(arr) {
  return arr.map((item) => {
    item.code = item.stockCode.replace(/[^\d]+/, "");
    return item;
  });
}

export default {
  data() {
    return {
      stockList: [],
      messageList: [],
      userId: userId,
      // sinceId: "",
      size: 0, //记录当前加载条数
      content: "",
      count: 150,
      introShow: true,
      listShow: false,
      // version: version,
      stock: "",
      imgSrc: "",
      announcement: "",
      shrink: {
        switch: false,
        aggregate: 0,
        text: "回到底部",
      },
      // numQuestions: "", //已提问次数
    };
  },
  components: { openImg },

  filters: {
    short(val) {
      if (val) {
        val = val.length >= 40 ? val.substr(0, 40) + "..." : val;
        return val;
      }
    },
  },

  computed: {},
  watch: {
    // numQuestions(num) {
    //   this.howdy = num >= 3 ? "今日提问次数已上限" : `您还有${3 - num}次提问机会`;
    // },
    stock: debounce(async function () {
      if (this.stock.length >= 1) {
        const { stocks } = await getStockList({ content: this.stock }).then(
          (back) => {
            if (back.status == 1) {
              let stocks = back.data.stocks;
              if (stocks.length > 0) {
                this.stockList = handler(stocks);

                this.listShow = true;
              }
            }
          }
        );
      } else {
        this.listShow = false;
      }
    }, 500),
    content: debounce(function () {
      if (this.content.length > 150) {
        this.content = this.content.substr(0, 150);
        return;
      }
      this.count = 150 - this.content.length;
      let day = localStorage.getItem("day");
    }, 500),
  },
  mounted() {
    this.getInfo();
    this.getLiveList();
    this.pushMessage();
    this.$nextTick(() => {
      // this.putDown();
      document.body.addEventListener("click", (e) => {
        if (e.target.className === "_stockCode") {
          var type = e.target.getAttribute("data-market");
          var code = e.target.getAttribute("data-code");
          this.link(type, code);
        }
      });
    });
  },
  methods: {
    async getInfo() {
      //获取公告
      await getInfo().then((back) => {
        console.log(back, "=====99999====");
        if (back.status == 1) {
          let data = back.data;
          if (status == 1 || data != undefined) {
            this.announcement = data.announcement;
          }
        }
      });
    },
    upIntro() {
      return;
      // this.introShow = !this.introShow;
    },
    tumble: debounce(function (e) {
      const { path } = e;
      if (
        path[0].scrollTop + path[0].clientHeight <
        path[0].scrollHeight - 10
      ) {
        this.shrink.switch = true;
      } else {
        this.shrink.switch = false;
        this.shrink.aggregate = 0;
        this.shrink.text = "回到底部";
      }
      if (path[0].scrollTop < 20) {
        this.getLiveList();
      }
    }, 300),
    //跳转个股详情
    link(type, code) {
      type = type == "SS" ? "1" : "0";
      window.prompt(
        "",
        `up://["open.stock",${Date.now()},{"setcode":"${type}","code":"${code}","type":"首页"}]`
      );
    },
    choose(exchangeSymbols, stockCode, stockName) {
      const code = stockCode.replace(/[^\d]+/, "");
      console.log(code);
      this.content = `${this.content}$${code + stockName}$`;
      // this.content = `${this.content}$${exchangeSymbols}-${stockCode + stockName}$`;
      behavior.event[0].eventSubject.stockCode =
        behavior.event[0].eventSubject.stockCode + "," + stockCode;
      behavior.event[0].eventSubject.stockName =
        behavior.event[0].eventSubject.stockName + "," + stockName;
      this.reset();
    },
    reset() {
      this.listShow = false;
      this.stock = "";
      this.stockList = [];
    },
    //聊天列表
    async getLiveList() {
      const box = this.$refs.chatBox;
      const boxed = box.scrollHeight; //记住上一次的滚动位置
      await getLiveList({
        productId: productId || window.localStorage.getItem("productId"),
        clientCentralToken: token,
        pageSize: this.size,
      }).then((back) => {
        if (back.status == 1) {
          let data = back.data;
          // console.log(data);
          if (data.length < 1) return;
          if (this.size == 0) {
            this.messageList = data.map((item) => {
              // item.content = item.content.replace(/(\r\n|\n|\r)/gm, "<br/>");
              // item.content = item.content.replace(/\s/gm, "&nbsp;");
              item.content = fn.higihLighttStock(item.content);
              item._publishTime = fn.timeFormat(
                item.pubtime,
                "yyyy-MM-dd HH:mm"
              );
              if (item.replyList) {
                item.replyList[0].content = fn.higihLighttStock(
                  item.replyList[0].content
                );
              }
              return item;
            });
            setTimeout(() => {
              this.putDown();
            }, 100);
          } else {
            this.messageList = data
              .map((item) => {
                item.content = fn.higihLighttStock(item.content);
                item._publishTime = fn.timeFormat(
                  item.pubtime,
                  "yyyy-MM-dd HH:mm"
                );
                if (item.replyList) {
                  item.replyList[0].content = fn.higihLighttStock(
                    item.replyList[0].content
                  );
                }
                return item;
              })
              .concat(this.messageList);

            //数据加载更多后定位滚动位置
            this.$nextTick(() => {
              box.scrollTop = box.scrollHeight - boxed;
            });
          }
          this.size = this.messageList.length;
        }
      });
    },
    viewImg(e) {
      console.log(e);
      if (e.path[0].tagName == "IMG") {
        this.imgSrc = e.path[0].src;
      }
    },

    //发送信息
    submit: debounce(async function () {
      // if (version != 5 && this.numQuestions >= 3) {
      //   return Toast("今日提问次数已上限");
      // }
      if (!this.content.trim()) {
        this.content = "";
        return Toast("输入不能为空");
      }
      this.content = this.content.replace(
        /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g,
        ""
      );

      // const { status } =
      await postLive({
        // productId: productId || window.localStorage.getItem("productId"),
        clientCentralToken: token,
        content: this.content,
      }).then((back) => {
        if (back.status == 1) {
          console.log("status", status);
          // if (status == 500003) {
          //   Toast("没有开启直播");
          // }
          this.content = "";
          this.size = 0;
          this.getLiveList();
        }
      });
    }, 300),

    //置底
    putDown() {
      const box = this.$refs.chatBox;
      this.shrink.aggregate = 0;
      this.shrink.text = "回到底部";
      this.$nextTick(() => {
        box.scrollTop = box.scrollHeight;
      });
    },
    //推送
    pushMessage() {
      // const uId = userId || window.localStorage.getItem("userId");
      // const pId = productId || window.localStorage.getItem("productId");
      const key = `0_7_0_2`; //直播间推送
      const self = this;

      fn.creatSocket(key, function (data) {
        console.log("socket", data.broadcasting);
        if (data.broadcasting.puiblisherid == userId) return;
        self.messageList = self.messageList.concat(
          [data.broadcasting].map((item) => {
            item.content = fn.higihLighttStock(item.content);
            item._publishTime = fn.timeFormat(item.pubtime, "yyyy-MM-dd HH:mm");
            if (item.replyList) {
              item.replyList[0].content = fn.higihLighttStock(
                item.replyList[0].content
              );
            }
            return item;
          })
        );
        self.shrink.aggregate++;
        if (self.shrink.aggregate <= 99) {
          self.shrink.text = `有${self.shrink.aggregate}条新消息`;
        } else {
          self.shrink.text = `有99+条新消息`;
        }
        if (!self.shrink.switch) {
          setTimeout(() => {
            self.putDown();
          }, 300);
        }

        console.log(self.messageList.length);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.live {
  width: 689px;
  height: 100%;
  border-radius: 8px;
  border: 1px solid rgba(69, 72, 85, 0.8);
  background: rgba(13, 18, 30, 0.8);
  // background: #fff;
}
.title {
  height: 52px;
  align-items: center;
  color: #e1e1e1;
  font-weight: 400;
  background: #262831;
  padding-left: 13px;
  border-radius: 8px 8px 0 0;
  .bhead {
    display: inline-block;
    width: 124px;
    height: 40px;
    line-height: 40px;
    font-size: 18px;
    padding-left: 50px;
    box-sizing: border-box;
    margin-right: 10px;
    color: #fec587;
    &.icon {
      background: url($PIC_URL + "/tlbypcWeb/extremeLive/zzds_icon.png")
        no-repeat left center;
    }
  }

  .titleTxt {
    letter-spacing: 1px;
    font-size: 16px;
    color: #bcbfc4;
    // width: 73%;
    // margin-right: 40px;
  }
}
.intro {
  box-sizing: border-box;
  color: #e9cbab;
  font-size: 16px;
  line-height: 22px;
  background: #473729;
  padding: 11px 13px;
  border: 1px solid #383a45;
  box-shadow: 0px 2px 7px 0px rgba(12, 17, 28, 0.7);
  .icon {
    margin: 0 auto;
    display: block;
    width: 9px;
    height: 10px;
    background: url($PIC_URL + "/tlbypcWeb/extremeLive/down.png") no-repeat
      center;
    padding: 10px;
    box-sizing: border-box;
    &.zk {
      background: url($PIC_URL + "/tlbypcWeb/extremeLive/up.png") no-repeat
        center;
    }
  }
}

.chat-items-wrap {
  width: 100%;
}
.noMore {
  padding-top: 100px;
  text-align: center;
  font-size: 18px;
  color: #fff;
}
.toDown {
  background-image: url($PIC_URL + "/tlbypcWeb/extremeLive/db_icon.png");
  background-repeat: no-repeat;
  background-position: right 10px center;
}
</style>
